package productsctl

import (
	"backenddev/shop_server/internal/logics"
	reqs "backenddev/shop_server/requests"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
)

func GetCategory(c *gin.Context) {

}

func AddCategory(c *gin.Context) {

}

func UpdateCategory(c *gin.Context) {

}

func DeleteCategory(c *gin.Context) {

}

func GetProduct(c *gin.Context) {

}

func UpdateProduct(c *gin.Context) {

}
func DeleteProduct(c *gin.Context) {

}

func AuditProduct(c *gin.Context) {

}

func GetHotProduct(c *gin.Context) {
	products, err := logics.GetHotProduct()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": products,
	})
}

func AddProduct(c *gin.Context) {
	req := &reqs.AddProductReq{}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(400, gin.H{"error": "Invalid input"})
		return
	}
	uploadDir := "uploads"
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法创建上传目录: " + err.Error()})
		return
	}
	// 1) 处理封面图 cover_image（单文件，可选）
	coverFile, err := c.FormFile("cover_image")
	if err == nil {
		ext := filepath.Ext(coverFile.Filename)
		coverName := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
		coverDst := filepath.Join(uploadDir, coverName)
		if err := c.SaveUploadedFile(coverFile, coverDst); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "保存封面图片失败: " + err.Error()})
			return
		}
		// 存相对访问路径，前端可以用 baseURL + req.CoverImage 显示
		req.CoverImage = "/" + filepath.ToSlash(filepath.Join(uploadDir, coverName))
	} else {
		req.CoverImage = ""
	}
	// 2) 处理多图 images（字段名 images，可上传多文件）
	form, err := c.MultipartForm()
	if err != nil && err != http.ErrNotMultipart {
		c.JSON(http.StatusBadRequest, gin.H{"error": "解析 multipart 表单失败: " + err.Error()})
		return
	}

	var savedPaths []string
	if form != nil {
		files := form.File["images"]
		for _, file := range files {
			ext := filepath.Ext(file.Filename)
			filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
			dst := filepath.Join(uploadDir, filename)
			if err := c.SaveUploadedFile(file, dst); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "保存图片失败: " + err.Error()})
				return
			}
			savedPaths = append(savedPaths, "/"+filepath.ToSlash(filepath.Join(uploadDir, filename)))
			time.Sleep(time.Microsecond)
		}
	}
	req.Images = savedPaths
	id, err := logics.AddProduct(req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "product created",
		"data": gin.H{
			"id":          id,
			"cover_image": req.CoverImage,
			"images":      req.Images,
		},
	})
}
